package com.ibeetl.admin.aod.web;

import com.ibeetl.admin.aod.entity.AodIndustry;
import com.ibeetl.admin.aod.service.AodIndustryService;
import com.ibeetl.admin.aod.service.excel.processor.AodIndustryImportProcessor;
import com.ibeetl.admin.aod.web.query.AodIndustryQuery;
import com.ibeetl.admin.core.annotation.Function;
import com.ibeetl.admin.core.file.FileItem;
import com.ibeetl.admin.core.file.FileService;
import com.ibeetl.admin.core.util.ConvertUtil;
import com.ibeetl.admin.core.util.DateUtil;
import com.ibeetl.admin.core.util.PlatformException;
import com.ibeetl.admin.core.util.ValidateConfig;
import com.ibeetl.admin.core.web.JsonResult;
import org.apache.commons.lang3.StringUtils;
import org.beetl.sql.core.engine.PageQuery;
import org.jxls.common.Context;
import org.jxls.util.JxlsHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;

/**
 * 行业类别 接口
 */
@Controller
public class AodIndustryController extends BaseController {

    private static final String MODEL = "/aod/aodIndustry";

    @Autowired
    protected AodIndustryService aodIndustryService;

    @Autowired
    protected AodIndustryImportProcessor aodIndustryImportProcessor;

    @Autowired
    FileService fileService;

    /**
     *
     * 主页
     * @return
     */
    @GetMapping(MODEL + "/index.do")
    @Function("aodIndustry.query")
    @ResponseBody
    public ModelAndView index() {
        ModelAndView view = new ModelAndView("/aod/aodIndustry/index.html") ;
        view.addObject("search", AodIndustryQuery.class.getName());
        return view;
    }

    /**
     * 编辑页面
     * @param id
     * @return
     */
    @GetMapping(MODEL + "/edit.do")
    @Function("aodIndustry.edit")
    @ResponseBody
    public ModelAndView edit(Integer id) {
        ModelAndView view = new ModelAndView("/aod/aodIndustry/edit.html");
        AodIndustry aodIndustry = aodIndustryService.queryById(id);
        view.addObject("aodIndustry", aodIndustry);
        return view;
    }

    /**
     * 新增 页面
     * @return
     */
    @GetMapping(MODEL + "/add.do")
    @Function("aodIndustry.add")
    @ResponseBody
    public ModelAndView add() {
        ModelAndView view = new ModelAndView("/aod/aodIndustry/add.html");
        return view;
    }

    /**
     * 分页查询
     * @param condition
     * @return
     */
    @PostMapping(MODEL + "/list.json")
    @Function("aodIndustry.query")
    @ResponseBody
    public JsonResult<PageQuery> list(AodIndustryQuery condition) {
        PageQuery page = condition.getPageQuery();
        aodIndustryService.queryByCondition(page);
        return JsonResult.success(page);
    }

    /**
     * 新增
     * @param aodIndustry
     * @return
     */
    @PostMapping(MODEL + "/add.json")
    @Function("aodIndustry.add")
    @ResponseBody
    public JsonResult add(@Validated(ValidateConfig.ADD.class)AodIndustry aodIndustry) {
        aodIndustryService.saveUnique(aodIndustry);
        return new JsonResult().success();
    }

    /**
     * 更新
     * @param aodIndustry
     * @return
     */
    @PostMapping(MODEL + "/update.json")
    @Function("aodIndustry.update")
    @ResponseBody
    public JsonResult<String> update(@Validated(ValidateConfig.UPDATE.class)  AodIndustry aodIndustry) {
        aodIndustryService.updateUnique(aodIndustry);
        return new JsonResult().success();
    }

    @GetMapping(MODEL + "/view.json")
    @Function("aodIndustry.query")
    @ResponseBody
    public JsonResult<AodIndustry>queryInfo(Integer id) {
        AodIndustry aodIndustry = aodIndustryService.queryById( id);
        return  JsonResult.success(aodIndustry);
    }

    /**
     * 删除
     * @param ids
     * @return
     */
    @PostMapping(MODEL + "/delete.json")
    @Function("aodIndustry.delete")
    @ResponseBody
    public JsonResult delete(String ids) {
        if (ids.endsWith(",")) {
            ids = StringUtils.substringBeforeLast(ids, ",");
        }
        List<Long> idList = ConvertUtil.str2longs(ids);
        aodIndustryService.batchDelAodIndustry(idList);
        return new JsonResult().success();
    }
    
    
    @PostMapping(MODEL + "/excel/export.json")
    @Function("aodIndustry.export")
    @ResponseBody
    public JsonResult<String> export(HttpServletResponse response,AodIndustryQuery condtion) {
        /**
         * 1)需要用你自己编写一个的excel模板
         * 2)通常excel导出需要关联更多数据，因此aodIndustryService.queryByCondition方法经常不符合需求，需要重写一个为模板导出的查询
         * 3)参考ConsoleDictController来实现模板导入导出
         */
        String excelTemplate ="excelTemplates/aod/aodIndustry/aodIndustry_export_template.xls";
        PageQuery<AodIndustry> page = condtion.getPageQuery();
        //取出全部符合条件的
        page.setPageSize(Integer.MAX_VALUE);
        page.setPageNumber(1);
        page.setTotalRow(Integer.MAX_VALUE);
        //本次导出需要的数据
        List<AodIndustry> list =aodIndustryService.queryByCondition(page).getList();
        try(InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream(excelTemplate)) {
            if(is==null) {
                throw new PlatformException("模板资源不存在："+excelTemplate);
            }
            FileItem item = fileService.createFileTemp("AodIndustry_" + DateUtil.now("yyyyMMddHHmmss")+".xls");
            OutputStream os = item.openOutpuStream();
            Context context = new Context();
            context.putVar("list", list);
            JxlsHelper.getInstance().processTemplate(is, os, context);
            os.close();
            //下载参考FileSystemContorller
            return  JsonResult.success(item.getPath());
        } catch (IOException e) {
            throw new PlatformException(e.getMessage());
        }
        
    }
    
    @PostMapping(MODEL + "/excel/import.do")
    @Function("aodIndustry.import")
    @ResponseBody
    public JsonResult importExcel(@RequestParam("file") MultipartFile file) throws Exception {
        try {
            aodIndustryImportProcessor.process(file, "excelTemplates/aod/aodIndustry/aodIndustry_mapping.xml");
            return JsonResult.success();
        } catch (RuntimeException e) {
            log.error("导入行业类别出错",e);
            return JsonResult.failMessage(e.getMessage());
        }catch (Exception e) {
            log.error("导入行业类别出错",e);
            return JsonResult.failMessage(e.getMessage());
        }
    }

}
